<template>
  <div>
    <a-spin :spinning="uploadSpinning" tip="数据保存中...">
      <a-alert
        type="error"
        :message="this.dataJson.errorMessage"
        v-if="alertiVisible"
        show-icon
        closable
        :after-close="handleClose"
        close-text="导出错误数据"
        style="margin: 24px;background-color: #fff1f0;"
      />
      <a-alert v-else :message="this.dataJson.errorMessage" type="success" show-icon style="margin: 24px;" />
      <div class="xq-form-wrapper pbox">
        <a-spin :spinning="spinning" class="xq-form-content">
          <XqTable
            :customize="FormJson['config']['table']['customize']"
            :scroll="{ x: columns.length * 150 }"
            :pagination="false"
            :dataSource="tableData"
            :columns="columns"
          >
            <template v-for="(col, index) in columns" v-slot:[`xq_${col.dataIndex}`]>
              <span :key="index">
                {{ col.customTitle }}
              </span>
            </template>
            <!-- eslint-disable-next-line prettier/prettier -->
            <template v-for="(col, index) in columns" v-slot:[col.dataIndex]="text, record">
              <div :key="index">
                <a-popover title="数据错误" placement="right">
                  <template slot="content">
                    <p>{{ record.errorReason }}</p>
                  </template>
                  <div class="triangle" v-if="col.dataIndex === record.typeName"></div>
                </a-popover>
                <span v-if="['email', 'wechat', 'companyName', 'companyAddress'].includes(col.dataIndex)">
                  <a-tooltip placement="top">
                    <template slot="title">
                      <span>{{ text }}</span>
                    </template>
                    <div class="overflows">
                      {{ text }}
                    </div>
                  </a-tooltip>
                </span>
                <span v-else>
                  {{ text }}
                </span>
              </div>
              <!-- <XqTableCell v-else :key="index" :record="record" :field="FormJson['fields'][col.dataIndex]" :dynamicData="dynamicData" /> -->
            </template>
          </XqTable>
          <div class="xq-form-content-pagination">
            <div class="xq-form-content-pagination-total">共 {{ total }} 条</div>
            <a-pagination
              v-model="pageNo"
              :page-size="pageSize"
              :total="total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :page-size-options="['10', '20', '50', '100']"
              @change="onPageChange"
              @showSizeChange="onPageSizeChange"
            />
          </div>
        </a-spin>
      </div>
      <div class="preview-btn">
        <a-button style="margin-right:12px;" @click="$emit('onAction', 0)">返回</a-button>
        <a-button type="primary" @click="onSubmit">
          下一步
        </a-button>
      </div>
    </a-spin>
  </div>
</template>

<script>
import axios from "axios";
import FormJson from "./FormJson";
import XqCurdMixin from "xqjr-plugin-form/mixins/XqCurdMixin";
import { getCrmCustomerImportDetails } from "../../api";

const curdMixin = new XqCurdMixin({
  FormJson,
  tableConfigKey: "table"
});

export default {
  mixins: [curdMixin],
  props: {
    dataJson: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      uploadSpinning: false,
      alertiVisible: false,
      spinning: false,
      tableData: [{ name: "ceshi", phone: "男" }],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      errorDataCount: 0
    };
  },
  created() {
    this.onGetCrmCustomerImportDetails();
  },
  methods: {
    async onGetCrmCustomerImportDetails() {
      try {
        this.spinning = true;
        const { data } = await getCrmCustomerImportDetails({
          recordId: this.dataJson.id,
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          isError: true,
          "orders[0].property": "gmtCreate",
          "orders[0].desc": true
        });
        this.tableData = data.entities;
        this.tableData.forEach(e => {
          const gender = ["男", "女", "未知"];
          e.gender = gender[e.gender - 1];
          const companyType = ["有限责任", "个人独资", "股权有限责任", "其他"];
          e.companyType = companyType[e.companyType - 1];
          const companyPersonSize = ["500以下", "500-1000", "1000-3000", "3000以上"];
          e.companyPersonSize = companyPersonSize[e.companyPersonSize - 1];
          e.typeName = this.getTypeName(e.errorReason);
        });
        this.total = data.entityCount;
        this.errorDataCount = data.entityCount;
        if (data.entityCount > 0) this.alertiVisible = true;
        setTimeout(() => (this.spinning = false), 500);
      } catch (err) {
        console.log("error log --> ", err);
        setTimeout(() => (this.spinning = false), 500);
      }
    },
    getTypeName(val) {
      const arr = [
        { k: "姓名", v: "name" },
        { k: "手机", v: "phone" },
        { k: "性别", v: "gender" },
        { k: "邮箱", v: "email" },
        { k: "微信", v: "wechat" },
        { k: "公司名称", v: "companyName" },
        { k: "公司地址", v: "companyAddress" },
        { k: "公司类型", v: "companyType" },
        { k: "公司规模", v: "companyPersonSize" }
      ];
      let n = null;
      if (val) {
        arr.some(e => {
          if (val.includes(e.k)) {
            n = e.v;
            return true;
          }
        });
      }
      return n;
    },
    onPageChange(page) {
      this.pageNo = page;
      this.onGetTalentPoolImportInfo();
    },
    onPageSizeChange(current, pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.onGetTalentPoolImportInfo();
    },
    handleClose() {
      const token = this.$store.state.auth.token;
      axios({
        url: `/hr/api/v1/crmCustomerImportRecords/getErrorCustomerData/${this.dataJson.id}`,
        method: "GET",
        responseType: "blob",
        headers: {
          token: token
        }
      })
        .then(res => {
          const link = document.createElement("a");
          const blob = new Blob([res.data], {
            type: "application/vnd.ms-excel"
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", "客户错误数据.xlsx");
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        })
        .catch(err => {
          console.log("error log --> ", err);
        });
    },
    async onSubmit() {
      this.uploadSpinning = true;
      const formData = new FormData();
      formData.append("recordId", this.dataJson.id);
      formData.append("isPublic", this.$route.name === "seaImports");
      axios({
        url: `/hr/api/v1/crmCustomerImportRecords/importCustomerInfo`,
        method: "post",
        data: formData,
        headers: {
          token: this.$store.state.auth.token
        }
      })
        .then(res => {
          setTimeout(() => {
            this.uploadSpinning = false;
            if (res.data.code === 200) {
              this.$emit("onActionS", 2, true, res.data.data);
            } else {
              this.$emit("onActionS", 2, false, res.data.msg);
            }
          }, 500);
        })
        .catch(err => {
          console.log("error log --> ", err);
          setTimeout(() => (this.uploadSpinning = false), 500);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.preview-btn {
  text-align: center;
}
.tags {
  display: flex;
  div {
    padding: 0 8px;
    height: 22px;
    line-height: 22px;
    margin-right: 8px;
    background: rgba(0, 0, 0, 0.04);
    border-radius: 2px;
    border: 1px solid rgba(0, 0, 0, 0.15);
    box-sizing: border-box;
  }
}
.triangle {
  position: absolute;
  top: 0;
  left: 16px;
  width: 0;
  height: 0;
  // border-top: 20px solid transparent;
  border-left: 10px solid red;
  // border-right: 20px solid transparent;
  border-bottom: 10px solid transparent;
}
.pbox {
  margin: 24px;
  ::v-deep .ant-table-tbody > tr > td {
    position: relative !important;
  }
}
.overflows {
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
